import Validator from 'el-form-validator';
import {modal} from '@/plugins/vxe-table'

/**
 * 深度复制obj
 * @param object
 * @returns {{}|*}
 */
export const deepCopy = (object) => {
	if (object === null || object === undefined || typeof object !== 'object') {
		return object;
	}
	let isArray = Array.isArray(object);
	let newObj = {};
	if (isArray) {
		newObj = [];
	}
	for (let key in object) {
		let v = object[key];

		if (typeof v === 'object') {
			newObj[key] = deepCopy(v);
		} else {
			if (isArray) {
				newObj.push(v);
			} else {
				newObj[key] = v;
			}
		}
	}

	return newObj;
};


/**
 *
 * @param source 	{Array}
 * @param id		{string}
 * @param parentId	{string}
 * @param children	{string}
 * @returns {[]}
 */
export const buildTree = (source, id = 'id', parentId = 'parentId', children = 'children') => {
	const cloneData = JSON.parse(JSON.stringify(source));

	let result = [];
	if (!Array.isArray(cloneData)) {
		return result;
	}

	cloneData.forEach(item => {
		delete item.children;
	});
	let map = {};
	cloneData.forEach(item => {
		map[item[id]] = item;
	});
	cloneData.forEach(item => {
		let parent = map[item[parentId]];
		if (parent) {
			(parent[children] || (parent[children] = [])).push(item);
		} else {
			result.push(item);
		}
	});

	return result;

}

/**
 * 简单生成最长10位的Uuid
 *
 * @param prefix    {string}    default: ''     前缀
 * @param size      {number}    default: 6      uuid长度 最长10位
 * @return          {string}
 */
export const generateUuid = (prefix = '', size = 6) => {
	return prefix + Math.random().toString(36).slice(2, size + 2);
};

export const importView = (view= '') => {
	if (typeof view !== 'string') return view;
	return function () {
		return import('@/views/' + view + '.vue');
	};
};



export default {
	/**
	 * form表单验证
	 * @param rules
	 * @param customMessages {Object | Array}
	 * @param customNames {Object}
	 * @returns {Array}
	 */
	formValidator(rules, customMessages = {} | [], customNames = {}) {
		return [
			value => {
				let r = Validator.valid(rules, value, customMessages, customNames);
				return r === true ? true : r.message
			}
		]
	},
	/**
	 * vex table 表单验证
	 * @param rules
	 * @param customMessages {Object | Array}
	 * @param customNames {Object}
	 * @returns {Object}
	 */
	vxeTableValidator(rules, customMessages = {} | [], customNames = {}) {
		return {
			validator: ({cellValue}) => {
				let r = Validator.valid(rules, cellValue, customMessages, customNames);
				return r;
			}
		}
	},
	/**
	 * 处理 http的响应结果
	 * @param res           {Object}        // response的数据 由axios提供返回
	 * @param ss            {boolean}       // 是否显示成功消息，默认不显示
	 * @param se            {boolean}       // 是否现象错误消息，默认显示
	 * @param sm            {string}        // 自定义成功消息
	 * @param em            {string}        // 自定义错误消息
	 * @returns {Promise<unknown>}
	 */
	async responseHandler(res, ss = false, se = true, sm = undefined, em = undefined) {
		if (!res || !res.data) {
			return Promise.reject(res);
		}
		if (res.data.success === true) {
			if (ss) {
				modal.message({message: (sm || res.data.message), status: 'success', id: 'success'})
			}
			return Promise.resolve(res.data);
		} else {
			if (se) {
				modal.message({message: em || res.data.message, status: 'error', id: 'error'})
			}
			return Promise.reject(res);
		}
	},
	/**
	 * 新的table结构生成
	 * @param option {import('interface').AdvTableColOption}
	 */
	gto(option) {
		return {
			...{align: 'center'},
			...option,
			params: Object.assign({}, option.params, {key: option.field})
		};
	},
	onConfirm(message) {
		return new Promise((resolve, reject) => {
			modal.confirm(message).then(type => {
				if (type === 'confirm') {
					return resolve()
				} else {
					reject();
				}
			})
		})
	},
	deepCopy,
	/**
	 *
	 * @param data
	 * @param columns
	 * @returns {{}}
	 */
	copyData(data, columns = []) {
		let obj = {};

		columns.forEach(column => {
			obj[column] = data[column];
		});
		return obj;
	},
	/**
	 * 通过 target 对比  不一样的的地方
	 * @param object {Object}
	 * @param target {Object}
	 * @returns {Object}
	 */
	objectSubtraction(target, object) {
		let newObject = {}
		if (!target) return newObject;
		Object.keys(target).map(item => {
			if (target[item] !== object[item]) {
				newObject[item] = target[item];
			}
		})
		return newObject
	},
	/**
	 *
	 * @param attrs {import('interface').GridAttr}
	 * @returns {*}
	 */
	tableAttrs (attrs) {
		return attrs;
	}
}